<template>
	<div class="table_header_manage">
		<div v-loading="loading" class="main_content">
			<div class="main_content_title">
				<div class="left">
					<template v-for="(item, index) in $route.meta.title">
						<span v-if="languageId === item.langId">{{ item.name }}</span>
					</template>
				</div>
			</div>
			<div class="content_body">
				<div class="tree_box">
					<div>
						<el-tree ref="tree" :data="treeData" node-key="id" draggable :check-strictly="true"
							:expand-on-click-node="false" :allow-drop="allowDrop" :allow-drag="allowDrag" @node-click="nodeClick" />
					</div>
				</div>
				<div v-loading="tableListLoading" class="detail_box">
					<div class="btn_box">
						<el-button type="primary" size="mini" @click.stop="handleCommand('add')">{{ $t('publicBtn.increase')
						}}</el-button>
					</div>
					<div v-if="tableList.length" class="list_box">
						<div class="list_header">
							<div class="table_item">
								<div />
								<div>{{ $t('publicFormLabel.name') }}</div>
								<div>key</div>
								<div>{{ $t('publicFormLabel.sort') }}</div>
								<div>{{ $t('publicFormLabel.operate') }}</div>
							</div>
						</div>
						<div class="list_body">
							<div class="list_body_content">
								<template v-for="(item, index) in tableList">
									<div :key="item.id" class="table_item">
										<div>{{ index + 1 }}</div>
										<div>{{ item.label }}</div>
										<div>{{ item.key }}</div>
										<div>{{ item.sortNum }}</div>
										<div @click.stop>
											<el-dropdown trigger="click" @command="(val) => handleCommand(val, item.id)">
												<span class="el-dropdown-link">
													<img src="@/assets/images/menu_more.svg">
												</span>
												<el-dropdown-menu slot="dropdown">
													<el-dropdown-item command="detail">{{ $t('publicBtn.detail') }}</el-dropdown-item>
													<el-dropdown-item command="edit">{{ $t('publicBtn.edit') }}</el-dropdown-item>
													<el-dropdown-item command="delete">{{ $t('publicBtn.delete') }}</el-dropdown-item>
												</el-dropdown-menu>
											</el-dropdown>
										</div>
									</div>
								</template>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<el-dialog v-loading="detailObjLoading" width="40%" :title="$t('text.tHFieldContent')"
			:visible.sync="detailObjVisible" append-to-body :before-close="handleDetailObjClose" :close-on-click-modal="false"
			custom-class="add_dialog">
			<!-- 语言动态标签页面 -->
			<elTabPane :isShow="isTag" :tagId="tagId" @tagClick="tagClick"></elTabPane>
			<el-form ref="detailObj" :model="detailObj" :rules="rules" label-width="auto" class="demo-ruleForm">
				<el-form v-for="(item, index) in detailObj.list" :ref="`detailObj${index}`" :model="item" :rules="rules"
					v-show="tagId === item.langId" :key="index" label-width="auto" class="demo-ruleForm">
					<el-form-item v-if="type !== 'add'" :label="$t('publicFormLabel.createTime')" prop="createTime">
						<el-input v-model="item.createTime" maxlength="10" :disabled="true" />
					</el-form-item>
					<el-form-item v-if="type !== 'add'" :label="$t('publicFormLabel.primaryKey')" prop="id">
						<el-input v-model="item.id" maxlength="10" :disabled="true" />
					</el-form-item>
					<template v-if="type !== 'detail'">
						<el-form-item :label="$t('formLabel.isImg')" prop="isImg">
							<el-radio-group v-model="item.isImg" @change="copyValue('list', 'isImg', item.isImg)">
								<el-radio :label=0>{{ $t('publicBtn.no') }}</el-radio>
								<el-radio :label=1>{{ $t('publicBtn.yes') }}</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item :label="$t('formLabel.displayFields')" prop="key">
							<el-input v-model="item.key" type="text" :placeholder="$t('placeholderTip.enter')"
								@change="copyValue('list', 'key', item.key)" />
						</el-form-item>
						<el-form-item :label="$t('formLabel.searchFields')" prop="searchField">
							<el-input v-model="item.searchField" type="text" :placeholder="$t('placeholderTip.enter')"
								@change="copyValue('list', 'searchField', item.searchField)" />
						</el-form-item>
						<el-form-item :label="$t('formLabel.sortFieldsName')" prop="keySort">
							<el-input v-model="item.keySort" type="text" :placeholder="$t('placeholderTip.enter')"
								@change="copyValue('list', 'keySort', item.keySort)" />
						</el-form-item>
						<el-form-item :label="$t('formLabel.fieldDisplayName')" prop="label">
							<el-input v-model="item.label" type="text" :placeholder="$t('placeholderTip.enter')" />
						</el-form-item>
						<el-form-item :label="$t('formLabel.menuId')" prop="menuId">
							<el-input v-model="item.menuId" type="text" :disabled="true" :placeholder="$t('placeholderTip.enter')" />
						</el-form-item>
						<el-form-item :label="$t('formLabel.isSearchable')" prop="searchEnable">
							<el-radio-group v-model="item.searchEnable" @change="copyValue('list', 'searchEnable', item.searchEnable)">
								<el-radio :label=0>{{ $t('publicBtn.no') }}</el-radio>
								<el-radio :label=1>{{ $t('publicBtn.yes') }}</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item :label="$t('formLabel.searchSQL')" prop="searchSql">
							<el-input v-model="item.searchSql" type="text" :placeholder="$t('placeholderTip.enter')"
								@change="copyValue('list', 'searchSql', item.searchSql)" />
						</el-form-item>
						<el-form-item :label="$t('formLabel.searchType')" prop="searchType">
							<el-radio-group v-model="item.searchType" @change="copyValue('list', 'searchType', item.searchType)">
								<el-radio :label=1>text</el-radio>
								<el-radio :label=2>select</el-radio>
								<el-radio :label=3>date</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item :label="$t('publicFormLabel.sort')" prop="sortNum">
							<el-input v-model="item.sortNum" type="number" min="0" :placeholder="$t('placeholderTip.enter')"
								@change="copyValue('list', 'sortNum', item.sortNum)" />
						</el-form-item>
						<el-form-item :label="$t('formLabel.width')" prop="width">
							<el-input v-model="item.width" type="number" min="0" :placeholder="$t('placeholderTip.enter')"
								@change="copyValue('list', 'width', item.width)" />
						</el-form-item>
					</template>
					<template v-if="type === 'detail'">
						<el-form-item :label="$t('formLabel.isImg')" prop="isImg">
							<el-radio-group :value="item.isImg">
								<el-radio :label=0>{{ $t('publicBtn.no') }}</el-radio>
								<el-radio :label=1>{{ $t('publicBtn.yes') }}</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item :label="$t('formLabel.displayFields')" prop="key">
							<el-input :value="item.key" type="text" :placeholder="$t('placeholderTip.enter')" />
						</el-form-item>
						<el-form-item :label="$t('formLabel.searchFields')" prop="searchField">
							<el-input :value="item.searchField" type="text" :placeholder="$t('placeholderTip.enter')" />
						</el-form-item>
						<el-form-item :label="$t('formLabel.sortFieldsName')" prop="keySort">
							<el-input :value="item.keySort" type="text" :placeholder="$t('placeholderTip.enter')" />
						</el-form-item>
						<el-form-item :label="$t('formLabel.fieldDisplayName')" prop="label">
							<el-input :value="item.label" type="text" :placeholder="$t('placeholderTip.enter')" />
						</el-form-item>
						<el-form-item :label="$t('formLabel.menuId')" prop="menuId">
							<el-input :value="item.menuId" type="text" :disabled="true" :placeholder="$t('placeholderTip.enter')" />
						</el-form-item>
						<el-form-item :label="$t('formLabel.isSearchable')" prop="searchEnable">
							<el-radio-group :value="item.searchEnable">
								<el-radio :label=0>{{ $t('publicBtn.no') }}</el-radio>
								<el-radio :label=1>{{ $t('publicBtn.yes') }}</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item :label="$t('formLabel.searchSQL')" prop="searchSql">
							<el-input :value="item.searchSql" type="text" :placeholder="$t('placeholderTip.enter')" />
						</el-form-item>
						<el-form-item :label="$t('formLabel.searchType')" prop="searchType">
							<el-radio-group :value="item.searchType">
								<el-radio :label=1>text</el-radio>
								<el-radio :label=2>select</el-radio>
								<el-radio :label=3>date</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item :label="$t('publicFormLabel.sort')" prop="sortNum">
							<el-input :value="item.sortNum" type="number" min="0" :placeholder="$t('placeholderTip.enter')" />
						</el-form-item>
						<el-form-item :label="$t('formLabel.width')" prop="width">
							<el-input :value="item.width" type="number" min="0" :placeholder="$t('placeholderTip.enter')" />
						</el-form-item>
					</template>
				</el-form>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="handleDetailObjClose">{{ type === 'detail' ? $t('el.popconfirm.close') :
					$t('el.popconfirm.cancelButtonText')
				}}</el-button>
				<el-button v-if="type !== 'detail'" type="primary" @click="handleDetailObjOk"
					v-loading.fullscreen.lock="fullscreenLoading">{{ $t('el.popconfirm.confirmButtonText') }}</el-button>
			</span>
		</el-dialog>
	</div>
</template>
<script>
import {
	addTableHeaderInfo,
	deleteTableHeaderByIds, getTableHeaderInfo, getTableHeaderMsgByMenuId, updateTableHeaderInfo
} from '@/api/table-config';
import elTabPane from '@/components/el-tab-pane/index'; //语言动态标签页面
import store from '@/store';

export default {
	name: 'TableHeaderManager',
	components: {
		elTabPane
	},
	data() {
		return {
			tagId: '',//语言id 默认id 
			isTag: false,
			loading: false,
			treeData: [],
			tableList: [],
			tableListLoading: false,
			detailObj: {
				list: [

				]
			},
			detailObjVisible: false,
			detailObjLoading: false,
			fullscreenLoading: false,
			menuId: '',
			type: 'add', // edit, add
			rules: {
				key: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					},
					{ validator: this.checkData, trigger: 'blur' }
				],
				label: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					}
				],
				sortNum: [
					{
						required: true,
						pattern: /^[0-9]\d*$/,
						message: this.$t('placeholderTip.enter') + '(>=0)',
						trigger: 'blur'
					}
				]
			}
		}
	},
	computed: {
		languageId() {
			// 固定语种ID  1:中文  2:英文 3:俄文 4:乌语
			return this.$store.getters.languageId
		},
		languageList() {
			return this.$store.getters.languageList.length > 0 ? this.$store.getters.languageList : JSON.parse(localStorage.getItem('languageList'))
		}
	},
	mounted() {
		window._vm = this
		this.init()
	},
	methods: {
		// 无多语言字段处理
		copyValue(key, key2, value) {
			this.detailObj[key].map(i => {
				i[key2] = value
			})
		},
		// 语言菜单处理
		tagClick(id) {
			if (id !== this.tagId) {
				this.resetForm('detailObj', 2)
				this.tagId = id
			}
		},
		// 重置表单
		resetForm(vaid, type) {
			// type 1 重置表单 2仅清空校验
			if (this.$refs[vaid] !== undefined) {
				this.$nextTick(() => {
					Promise.all([
						//数组部分的表单，用map返回验证函数的调用
						...this.detailObj.list.map((item, index) => {
							var refs = `detailObj${index}`
							let valiForm = this.$refs?.[refs].validate
								? this.$refs?.[refs]
								: this.$refs?.[refs][0];
							if (type === 1) {
								valiForm.resetFields()
							} else {
								valiForm.clearValidate()
							}
						})
					])
				})
			}
		},
		checkData(rule, value, callback) {
			if (value) {
				if (/[\u4E00-\u9FA5]/g.test(value)) {
					callback(new Error(this.$t('text.noInChinese')))
				} else {
					callback()
				}
			}
			callback()
		},
		handleDetailObjOk() {
			Promise.all([
				//非数组部分的表单
				// this.validateForm("detailObj"),
				//数组部分的表单，用map返回验证函数的调用
				...this.detailObj.list.map((item, index) => {
					if (this.tagId === item.langId) {
						// 当前语种 表单校验
						return this.validateForm(`detailObj${index}`)
					}
				})
			]).then((res) => {
				if (res) {
					// 全部表单验证通过
					var next = null,
						message = ''
					this.detailObjLoading = true
					var data = JSON.parse(JSON.stringify(this.detailObj.list))
					this.fullscreenLoading = true
					if (this.type === 'edit') {
						next = updateTableHeaderInfo
						message = this.$t('text.editSucceedTip')
					} else if (this.type === 'add') {
						next = addTableHeaderInfo
						message = this.$t('text.addSucceedTip')
					}
					next({ t: data })
						.then(res => {
							if (res.code === 200) {
								this.$message({
									message,
									type: 'success'
								})
								this.fullscreenLoading = false
								this.handleDetailObjClose()
								this.showTableList()
							}
						})
						.finally(() => {
							this.detailObjLoading = false
							this.fullscreenLoading = false
						})
				}
			})
				.catch((err) => {
					console.log(err);
				});
		},
		validateForm(refs) {
			//获取到form表单的dom，如果是对象直接拿到，如果是数组，就拿第一个
			//elementui对循环的form包装成了数组
			let valiForm = this.$refs?.[refs].validate
				? this.$refs?.[refs]
				: this.$refs?.[refs][0];
			return new Promise((resolve, reject) => {
				//在Promise里进行验证，如果通过就resolve()
				valiForm.validate((res) => {
					if (res) {
						resolve(res);
					} else reject();
				});
			});

		},

		getNumber(tar) {
			var num = Number(tar)
			if (isNaN(num)) {
				return 0
			} else {
				return num
			}
		},
		handleDetailObjClose() {
			this.detailObjVisible = false
			this.detailObjLoading = false
		},
		handleCommand(val, id) {
			this.type = val
			this.info = { list: [] }
			this.resetForm('detailObj', 1)
			switch (val) {
				case 'add':
					if (this.menuId) {
						this.$nextTick(() => {
							this.detailObj.list = this.setFormData()
						})
						this.tagId = this.languageId
						this.isTag = true
						this.detailObjVisible = true
					} else {
						this.$message({
							message: this.$t('text.pleaseSelectMenu'),
							type: 'warning'
						})
					}
					break
				case 'edit':
				case 'detail':
					this.tagId = this.languageId
					this.isTag = true
					this.detailObjVisible = true
					this.getDetailData(id)
					break
				case 'delete':
					this.$confirm(this.$t('delConfirm.isDelete'), this.$t('delConfirm.tip'), {
						confirmButtonText: this.$t('delConfirm.confirmButtonText'),
						cancelButtonText: this.$t('delConfirm.cancelButtonText'),
						type: 'warning'
					}).then(() => {
						deleteTableHeaderByIds({
							ids: id
						}).then(res => {
							if (res.code === 200) {
								this.$message({
									message: this.$t('text.delSucceedTip'),
									type: 'success'
								})
								this.showTableList()
							}
						})
					})
					break
				default:
					break
			}
		},
		// 多表单处理
		setFormData() {
			var arr = []
			this.languageList.map(i => {
				var obj = {
					langId: i.id,
					createTime: '', // 创建时间
					isImg: 0, // 是否图片
					key: '', // 显示字段
					searchField: '', // 搜索字段
					keySort: '', // 排序字段
					label: '', // 字段显示命
					menuId: this.menuId, // 菜单id
					searchEnable: 0, // 是否可搜索
					searchSql: '', // 搜索sql
					searchWhere: '', // 查询条件
					searchType: 1, // 搜索类型  1text 2select,3 date
					sortNum: '', // 排序
					width: 200 // 宽度
				}
				arr.push(obj)
			})
			return arr
		},
		getDetailData(id) {
			this.detailObjLoading = true
			getTableHeaderInfo(id)
				.then(res => {
					if (res.code === 200 && res.data.t.length > 0) {
						this.checkDetailData(res.data.t)
					}
				})
				.catch(error => {
					console.error(error)
				})
				.finally(() => {
					this.detailObjLoading = false
				})
		},
		checkDetailData(data) {
			var newArr = []
			var arr = data
			var newObj = arr[0]
			this.languageList.map(i => {
				var obj = {
					langId: i.id, //多语种langId
					id: newObj.id,
					createTime: newObj.createTime, // 创建时间
					isImg: newObj.isImg, // 是否图片
					key: newObj.key, // 显示字段
					searchField: newObj.searchField, // 搜索字段
					keySort: newObj.keySort, // 排序字段
					label: '', // 字段显示命
					menuId: newObj.menuId, // 菜单id
					searchEnable: newObj.searchEnable, // 是否可搜索
					searchSql: newObj.searchSql, // 搜索sql
					searchWhere: newObj.searchWhere, // 查询条件
					searchType: newObj.searchType, // 搜索类型  1text 2select,3 date
					sortNum: newObj.sortNum, // 排序
					width: newObj.width // 宽度
				}
				newArr.push(obj)
			})
			data.map(j => {
				// 根据id进行对象替换 
				let index = newArr.findIndex(e =>
					e.langId == j.langId
				)
				if (index > -1) {
					newArr[index] = j
				}
			})
			this.detailObj.list = newArr

		},
		nodeClick(data) {
			// console.log('nodeClick : ', data.id)
			this.menuId = data.id
			this.showTableList()
		},
		showTableList() {
			this.tableListLoading = true
			this.tableList = []
			getTableHeaderMsgByMenuId(this.menuId)
				.then(res => {
					if (res.code === 200) {
						this.tableList = res.data.list
					}
				})
				.finally(() => {
					this.tableListLoading = false
				})
		},
		allowDrop(draggingNode, dropNode, type) {
			// console.log('allowDrop : ', draggingNode, dropNode, type);
			if (draggingNode.data.parentId === '0') {
				if (dropNode.data.parentId !== '0') {
					return false
				} else if (type === 'inner') {
					return false
				}
			} else {
				if (dropNode.data.parentId === '0') {
					if (type !== 'inner') {
						return false
					}
				}
			}
			return true
		},
		allowDrag(draggingNode) {
			return false
		},
		init() {
			this.treeData = []
			this.loading = false
			this.tableListLoading = false
			this.getTreeData()
		},
		getTreeData() {
			var routerList = store.getters.menuList
			this.treeData = this.checkTreeData(routerList)
		},
		checkTreeData(data) {
			var list = []
			data.forEach((item, index) => {
				var obj = JSON.parse(JSON.stringify(item))
				obj.children = []
				obj.orderNum = index
				if (obj.title.length > 0) {
					obj.title.map(i => {
						if (this.languageId === i.langId) {
							obj.label = i.name
						}
					})
				}
				if (item.children) {
					obj.children = this.checkTreeData(item.children)
				}
				list.push(obj)
			})
			return list
		},
		treeSort(data, parentId) {
			var list = []
			data.forEach((item, index) => {
				var obj = JSON.parse(JSON.stringify(item))
				obj.orderNum = index + 1
				obj.children = []
				obj.parentId = parentId
				if (item.children) {
					obj.children = this.treeSort(item.children, item.id)
				}
				list.push(obj)
			})
			return list
		}
	}
}
</script>
<style lang="scss">
.table_header_manage {
	height: 100%;
	width: 100%;
	padding: 20px;
	box-sizing: border-box;
	overflow: hidden;

	&>.main_content {
		width: 99.9%;
		height: 100%;
		overflow: hidden;

		&>.main_content_title {
			margin-bottom: 10px;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
		}

		&>.content_body {
			display: flex;
			flex-direction: row;
			justify-content: flex-start;
			box-sizing: border-box;
			border: 1px solid #dcdfe6;
			overflow: hidden;
			width: 100%;
			height: calc(100% - 38px);

			.tree_box {
				// flex: 1 1 0;
				width: auto;
				min-width: 260px;
				height: 100%;
				box-sizing: border-box;
				padding: 20px;
				border-right: 1px solid #dcdfe6;

				&>div {
					height: 100%;
					overflow: hidden auto;

					.el-tree-node__content {
						height: 40px;
					}

					.is-current {
						&>.el-tree-node__content {
							background-color: #d8b581;
							color: #fff;
						}
					}

					& {
						.is-current>.el-tree-node__content .custom-tree-node {
							flex: 1 1 0;
							display: flex;
							align-items: center;
							justify-content: space-between;

							.item_btn {
								display: inline-block;
							}
						}
					}

					.item_btn {
						display: none;
					}
				}
			}

			.detail_box {
				flex: 2 2 0;
				height: 100%;
				box-sizing: border-box;
				padding: 20px;

				.btn_box {
					display: flex;
					flex-direction: row;
					justify-content: flex-end;
					align-items: center;
					height: 40px;
				}

				.list_box {
					height: calc(100% - 40px);
					overflow: hidden;

					.list_header {
						border-top: 1px solid #dcdfe6;
					}

					.list_body {
						height: calc(100% - 50px);
						width: calc(100% + 17px);
						box-sizing: content-box;
						overflow: hidden auto;

						.list_body_content {
							min-height: calc(100% + 1px);
						}
					}

					.table_item {
						width: 100%;
						height: 50px;
						display: flex;
						flex-direction: row;
						justify-content: flex-start;
						align-items: center;
						box-sizing: border-box;
						text-align: center;

						div {
							border-left: 1px solid #dcdfe6;
							border-top: 1px solid #dcdfe6;
							height: 50px;
							line-height: 50px;
							box-sizing: border-box;
							white-space: nowrap;

							&:nth-of-type(1) {
								flex: 0 0 auto;
								width: 50px;
							}

							&:nth-of-type(2) {
								flex: 2 2 0;
							}

							&:nth-of-type(3) {
								flex: 1 1 0;
							}

							&:nth-of-type(4) {
								width: 200px;
							}

							&:nth-of-type(5) {
								width: 140px;

								&>div {
									border: none;
								}
							}

							&:last-of-type {
								border-right: 1px solid #dcdfe6;
							}
						}

						&:last-of-type {
							border-bottom: 1px solid #dcdfe6;
						}
					}
				}
			}
		}
	}

	.btn_box {
		text-align: right;
	}

	.el-dialog {
		margin-top: 10vh !important;
		height: 80vh;

		.el-dialog__header {
			box-sizing: border-box;
			border-bottom: 1px solid #dcdfe6;
			height: 55px;
		}

		.el-dialog__body {
			height: calc(100% - 115px);
			overflow: auto !important;
			padding: 20px;

			&>div {
				width: 100%;
				height: 100%;
				overflow: auto;
				box-sizing: border-box;
				border: 1px solid #dcdfe6;
				padding: 20px;

				.edit_item_box {
					display: flex;
					flex-direction: row;
					justify-content: flex-start;
					align-items: center;
					height: 50px;
					padding: 0 10px;

					// border-bottom: 1px solid #dcdfe6;
					&>.name {
						width: 80px;
					}

					&>.type {
						flex: 0 0 auto;
					}

					&>.value {
						flex: 1 1 0;
						margin: 0 20px;
						box-sizing: border-box;

						input {
							width: 100%;
							height: 40px;
							line-height: 40px;
							border: 1px solid #dcdfe6;
							outline: none;
							border-radius: 5px;
							padding: 0 10px;

							&:focus {
								border: 1px solid #29b5ff;
							}
						}
					}
				}
			}
		}

		.el-dialog__footer {
			box-sizing: border-box;
			border-top: 1px solid #dcdfe6;
			height: 60px;
			padding: 10px 20px !important;
		}
	}
}
</style>
<style lang="scss">
.add_dialog {
	height: calc(100% - 30vh) !important;
	position: relative;

	.el-dialog__header {
		border-bottom: 1px solid #e4e4e4;
		text-align: left;
	}

	.el-dialog__body {
		height: calc(100% - 125px);

		&>.el-form {
			margin-top: 15px;
			height: calc(100% - 30px);
			overflow: auto;
		}
	}

	.el-dialog__footer {
		border-top: 1px solid #e4e4e4;
		text-align: right;
	}

	.el-button:hover,
	.el-button:focus {
		color: #000;
	}
}
</style>
